package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

	private Socket socket;
	private Map<String, Context> contextMap;

	public RequestProcessor(Socket socket, Map<String, Context> contextMap) {
		this.socket = socket;
		this.contextMap = contextMap;
	}

	@Override
	public void run() {
		try {
			InputStream inputStream = socket.getInputStream();

			// 封装Request对象和Response对象
			Request request = new Request(inputStream);
			Response response = new Response(socket.getOutputStream());

			Context context = contextMap.get(request.getContextName());
			// 静态资源处理
			if (context == null) {
				response.outputHtml(request.getUrl());
			} else {
				String requestMapping = request.getUrl();
				if (requestMapping.length() > request.getContextName().length() + 1) {
					requestMapping = requestMapping.substring(request.getContextName().length()+1);
				}
				
				if (context.getServletMap().get(requestMapping) == null) {
					response.outputHtml(request.getUrl());
				} else {
					// 动态资源servlet请求
					HttpServlet httpServlet = context.getServletMap().get(requestMapping);
					httpServlet.service(request, response);
				}
			}

			socket.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
